package com.zhoufeng.udp.service;

import com.zhoufeng.common.Common;
import com.zhoufeng.db.DbMng;
import com.zhoufeng.model.DeviceConfigure;
import com.zjhbkj.xinfen.commom.Global;
import com.zjhbkj.xinfen.db.DBMgr;
import com.zjhbkj.xinfen.model.MsgInfo;
import com.zjhbkj.xinfen.model.RcvComsModel;
import com.zjhbkj.xinfen.model.SendComsModel;
import com.zjhbkj.xinfen.util.CommandUtil;

import de.greenrobot.event.EventBus;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UDPServerForApp implements Runnable {
	private DatagramSocket mReceiveSocket;
	private DatagramSocket mSendSocket;
	private byte[] msg;
	private boolean onGoinglistner;

	public UDPServerForApp() {
		byte[] arrayOfByte = new byte[Common.COMMAND_LENGTH];
		this.msg = arrayOfByte;
		this.onGoinglistner = true;
		init();
	}

	private void init() {
		try {
			if (this.mReceiveSocket == null) {
				DatagramSocket localDatagramSocket1 = new DatagramSocket(null);
				this.mReceiveSocket = localDatagramSocket1;
				this.mReceiveSocket.setReuseAddress(true);
				DatagramSocket localDatagramSocket2 = this.mReceiveSocket;
				int i = Common.UDP_APP_PORT;
				InetSocketAddress localInetSocketAddress = new InetSocketAddress(i);
				localDatagramSocket2.bind(localInetSocketAddress);
			}
			DatagramSocket localDatagramSocket3 = new DatagramSocket();
			this.mSendSocket = localDatagramSocket3;
			return;
		} catch (SocketException localSocketException) {
			String str = localSocketException.toString();
			localSocketException.printStackTrace();
		}
	}

	public void closeConnection() {
		if (this.mReceiveSocket != null) {
			this.mReceiveSocket.close();
			this.mReceiveSocket = null;
		}
		if (this.mSendSocket == null)
			return;
		this.mSendSocket.close();
		this.mSendSocket = null;
	}

	public void run() {
		byte[] arrayOfByte1 = this.msg;
		int i = this.msg.length;
		DatagramPacket localDatagramPacket = new DatagramPacket(arrayOfByte1, i);
		while (true) {
			if (!this.onGoinglistner)
				return;
			try {
				this.mReceiveSocket.receive(localDatagramPacket);
				// RcvComsModel localRcvComsModel = new RcvComsModel();
				byte[] arrayOfByte2 = localDatagramPacket.getData();
				System.out.println(arrayOfByte2.length);
				String ss = complieData(arrayOfByte2);
				if (ss != null && ss.length() > 65)
					ss = ss.substring(0, 65).trim();
				
				// boolean bool =
				// localRcvComsModel.receiveCommand(arrayOfByte2);
				if (ss != null && ss.length() == 65) {
					String[] ssarr = ss.split(" ");
					
					if("40".equals(ssarr[0]) && "DA".equals(ssarr[1])){
						saveDeviceDataAndSendDeviceConfig(localDatagramPacket, ss);
					}else if("AA".equals(ssarr[0]) && "EA".equals(ssarr[1])){
						saveDeviceConfigAndSendDeviceDataToAPP(localDatagramPacket, ss);
					}
					
					
					
					
				} else {
					String send = "数据错误，保存失败！";
					byte[] bsend = send.getBytes();
					InetAddress addr = localDatagramPacket.getAddress();
					int port = localDatagramPacket.getPort();
					DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
					this.mReceiveSocket.send(sendPacket);
				}
			} catch (IOException localIOException) {
				localIOException.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 
	 * 接收APP配置信息并发送设备数据信息到APP
	 * @param localDatagramPacket
	 * @param ss
	 * @throws IOException
	 */
	private void saveDeviceConfigAndSendDeviceDataToAPP(DatagramPacket localDatagramPacket, String ss) throws IOException {
		boolean bool = DbMng.saveDeviceConfig(ss, null);
		int j = this.msg.length;
		localDatagramPacket.setLength(j);
		if (bool) {
			// DBMgr.saveModel(localRcvComsModel);
			// EventBus.getDefault().post(localRcvComsModel);
			// send(localDatagramPacket);
			
			String s = DeviceConfigure.me.getConfigureinfotoStr(ss.split(" ")[19] + ss.split(" ")[18] + ss.split(" ")[17]);
			byte[] bsend = null;
			if(s != null){
				bsend = CommandUtil.getCommand(s);
			
			
//						String send = "接收成功";
//						byte[] bsend = send.getBytes();
				InetAddress addr = localDatagramPacket.getAddress();
				int port = localDatagramPacket.getPort();
				DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
				this.mReceiveSocket.send(sendPacket);
			}
		} else {
			String send = "保存失败";
			byte[] bsend = send.getBytes();
			InetAddress addr = localDatagramPacket.getAddress();
			int port = localDatagramPacket.getPort();
			DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
			this.mReceiveSocket.send(sendPacket);
		}
	}

	
	/**
	 * 
	 * 接收设备数据信息和发送配置到设别
	 * @param localDatagramPacket
	 * @param ss
	 * @throws IOException
	 */
	private void saveDeviceDataAndSendDeviceConfig(DatagramPacket localDatagramPacket, String ss) throws IOException {
		boolean bool = DbMng.saveinfo(ss);
		int j = this.msg.length;
		localDatagramPacket.setLength(j);
		if (bool) {
			// DBMgr.saveModel(localRcvComsModel);
			// EventBus.getDefault().post(localRcvComsModel);
			// send(localDatagramPacket);
			
			String s = DeviceConfigure.me.getConfigureinfotoStr(ss.split(" ")[19] + ss.split(" ")[18] + ss.split(" ")[17]);
			byte[] bsend = null;
			if(s != null){
				bsend = CommandUtil.getCommand(s);
			
			
//						String send = "接收成功";
//						byte[] bsend = send.getBytes();
				InetAddress addr = localDatagramPacket.getAddress();
				int port = localDatagramPacket.getPort();
				DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
				this.mReceiveSocket.send(sendPacket);
			}
		} else {
			String send = "保存失败";
			byte[] bsend = send.getBytes();
			InetAddress addr = localDatagramPacket.getAddress();
			int port = localDatagramPacket.getPort();
			DatagramPacket sendPacket = new DatagramPacket(bsend, bsend.length, addr, port);
			this.mReceiveSocket.send(sendPacket);
		}
	}

	private String complieData(byte[] data) {

		String retstr = null;
		retstr = new String(data);
		if (data.length < 65) {
			retstr = CommandUtil.bytesToHexString(data);

//			String s = null;
//			byte byte1 = data[0];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[1];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[2];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[3];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[4];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[5];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[6];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[7];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[8];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[9];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[10];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[11];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[12];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[13];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[14];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[15];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[16];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[17];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[18];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[19];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[20];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);
//
//			byte1 = data[21];
//			s = Common.bytesToHexString(byte1);
//			System.out.println(s);

		}

		// return localRcvComsModel;
		return retstr;
	}

	public void send(DatagramPacket paramDatagramPacket) {
		SendComsModel localSendComsModel = (SendComsModel) DBMgr.getHistoryData(SendComsModel.class, "EA");
		if (localSendComsModel == null)
			return;
		byte[] arrayOfByte = CommandUtil.getCommand(localSendComsModel.toString());
		int i = arrayOfByte.length;
		InetAddress localInetAddress1 = paramDatagramPacket.getAddress();
		int j = paramDatagramPacket.getPort();
		DatagramPacket localDatagramPacket = new DatagramPacket(arrayOfByte, i, localInetAddress1, j);
		try {
			this.mSendSocket.send(localDatagramPacket);
			EventBus localEventBus1 = EventBus.getDefault();
			StringBuilder localStringBuilder1 = new StringBuilder("消息发送成功");
			InetAddress localInetAddress2 = paramDatagramPacket.getAddress();
			StringBuilder localStringBuilder2 = localStringBuilder1.append(localInetAddress2).append(":");
			int k = paramDatagramPacket.getPort();
			String str1 = new Integer(k).toString();
			localEventBus1.post(str1);
			return;
		} catch (IOException localIOException) {
			localIOException.printStackTrace();
			EventBus localEventBus2 = EventBus.getDefault();
			StringBuilder localStringBuilder3 = new StringBuilder("消息发送失败.");
			String str2 = localIOException.toString();
			String str3 = str2;
			localEventBus2.post(str3);
		}
	}

	public void stopAcceptMessage() {
		this.onGoinglistner = false;
	}

	public static abstract interface DataRecvListener {
		public abstract void onRecv(MsgInfo paramMsgInfo);
	}

	public static void main(String[] args) {
		new UDPServerForApp().run();
	}
}